package com.lzc.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzc.security.enums.LoginType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class MyAuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        System.out.println("登录失败");
        if (LoginType.JSON.equals(securityProperties.getLoginType())) {
            Map<String, Object> map = new HashMap<>();
            map.put("code", "1");
            map.put("msg", "失败");
            map.put("data", exception.getMessage());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(map));
        } else {
            super.setDefaultFailureUrl(securityProperties.getSetDefaultFailureUrl());
            super.onAuthenticationFailure(request, response, exception);
        }
    }
}
